package com.spring.security.app.config;

import com.spring.security.core.properties.SecurityProperties;
import com.spring.security.core.properties.oauth.OAuth2ClientProperties;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.ArrayList;
import java.util.List;

/**
 * oauth认证服务器配置
 *
 * @author seabed_moon
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class SpringAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    private final SecurityProperties securityProperties;

    private final TokenStore redisTokenStore;

//    @Autowired(required = false)
//    private JwtAccessTokenConverter jwtAccessTokenConverter;

    private final TokenEnhancer jwtTokenEnhancer;


    /**
     * 端点配置
     *
     * @param endpoints endpoints
     * @throws Exception ex
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(redisTokenStore)
                .userDetailsService(userDetailsService);
        if (null != jwtTokenEnhancer) {
            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            List<TokenEnhancer> tokenEnhancers = new ArrayList<>(2);
            tokenEnhancers.add(jwtTokenEnhancer);
            tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
            endpoints
                    .tokenEnhancer(tokenEnhancerChain);
        }

    }

    /**
     * tokenKey的访问权限表达式配置
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()");
    }

    /**
     * 客户端配置
     *
     * @param clients clients
     * @throws Exception ex
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if (ArrayUtils.isNotEmpty(securityProperties.getOauth2().getClients())) {
            for (int i = 0, len = securityProperties.getOauth2().getClients().length; i < len; i++) {
                OAuth2ClientProperties oAuth2ClientProperties = securityProperties.getOauth2().getClients()[i];
                builder.withClient(oAuth2ClientProperties.getClientId())
                       .secret(oAuth2ClientProperties.getClientSecret())
                       .authorizedGrantTypes("refresh_token", "password", "authorization_code")
                       //令牌超时时间 单位:s
                       .accessTokenValiditySeconds(oAuth2ClientProperties.getAccessTokenValiditySeconds())
                       .refreshTokenValiditySeconds(oAuth2ClientProperties.getAccessTokenValiditySeconds())
                       .scopes("all", "read", "write");
            }
        } else {
            //默认的配置
            builder.withClient("sunlands")
                   .secret("sunlandssecret")
                   //令牌超时时间 单位:s
                   .accessTokenValiditySeconds(7200)
                   .authorizedGrantTypes("refresh_token", "password")
                   .scopes("all", "read", "write");
        }
    }
}
